<template>
  <div class="admin-dashboard">
    <div class="admin-header">
      <h1>动物乐园后台管理系统</h1>
      <div class="header-actions">
        <span class="welcome-text">欢迎管理员</span>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>
    </div>
    
    <div class="admin-layout">
      <aside class="sidebar">
        <nav class="admin-nav">
          <ul>
            <li>
              <router-link to="/admin/dashboard" class="nav-item" active-class="active">
                <span class="nav-icon">📊</span>
                <span class="nav-text">仪表盘</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/animals" class="nav-item" active-class="active">
                <span class="nav-icon">🐾</span>
                <span class="nav-text">动物管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/categories" class="nav-item" active-class="active">
                <span class="nav-icon">📂</span>
                <span class="nav-text">分类管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/users" class="nav-item" active-class="active">
                <span class="nav-icon">👥</span>
                <span class="nav-text">用户管理</span>
              </router-link>
            </li>
          </ul>
        </nav>
      </aside>
      
      <main class="main-content">
        <div class="page-header">
          <h2>动物管理</h2>
          <button @click="showAddAnimalForm = true" class="add-btn">
            <span>+</span> 添加动物
          </button>
        </div>
        
        <div class="search-filter">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索动物名称..."
            class="search-input"
          />
          <select v-model="selectedCategory" class="filter-select">
            <option value="">全部分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>
        
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>动物名称</th>
                <th>分类</th>
                <th>栖息地</th>
                <th>濒危状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="animal in filteredAnimals" :key="animal.id">
                <td>{{ animal.id }}</td>
                <td>{{ animal.name }}</td>
                <td>{{ getCategoryName(animal.categoryId) }}</td>
                <td>{{ animal.habitat }}</td>
                <td>
                  <span :class="`status-badge ${getStatusClass(animal.endangeredLevel)}`">
                    {{ getEndangeredText(animal.endangeredLevel) }}
                  </span>
                </td>
                <td>{{ formatDate(animal.createdAt) }}</td>
                <td>
                  <div class="action-buttons">
                    <button @click="editAnimal(animal)" class="edit-btn">编辑</button>
                    <button @click="deleteAnimal(animal.id)" class="delete-btn">删除</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="pagination">
          <button 
            @click="currentPage--" 
            :disabled="currentPage === 1"
            class="pagination-btn"
          >
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button 
            @click="currentPage++" 
            :disabled="currentPage === totalPages"
            class="pagination-btn"
          >
            下一页
          </button>
        </div>
        
        <!-- 添加/编辑动物模态框 -->
        <div v-if="showAddAnimalForm || showEditForm" class="modal-overlay" @click="closeModal">
          <div class="modal-content" @click.stop>
            <div class="modal-header">
              <h3>{{ showEditForm ? '编辑动物' : '添加动物' }}</h3>
              <button @click="closeModal" class="close-btn">×</button>
            </div>
            <div class="modal-body">
              <form @submit.prevent="submitForm">
                <div class="form-group">
                  <label for="name">动物名称</label>
                  <input 
                    type="text" 
                    id="name" 
                    v-model="formData.name"
                    required
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="categoryId">分类</label>
                  <select 
                    id="categoryId" 
                    v-model="formData.categoryId"
                    required
                    class="form-input"
                  >
                    <option value="">请选择分类</option>
                    <option v-for="category in categories" :key="category.id" :value="category.id">
                      {{ category.name }}
                    </option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="habitat">栖息地</label>
                  <input 
                    type="text" 
                    id="habitat" 
                    v-model="formData.habitat"
                    required
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="description">描述</label>
                  <textarea 
                    id="description" 
                    v-model="formData.description"
                    rows="4"
                    class="form-input"
                  ></textarea>
                </div>
                <div class="form-group">
                  <label for="endangeredLevel">濒危状态</label>
                  <select 
                    id="endangeredLevel" 
                    v-model="formData.endangeredLevel"
                    class="form-input"
                  >
                    <option value="0">无危</option>
                    <option value="1">近危</option>
                    <option value="2">易危</option>
                    <option value="3">濒危</option>
                    <option value="4">极危</option>
                  </select>
                </div>
                <div class="form-actions">
                  <button type="button" @click="closeModal" class="cancel-btn">取消</button>
                  <button type="submit" class="submit-btn">
                    {{ showEditForm ? '更新' : '添加' }}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AnimalManagementView',
  data() {
    return {
      animals: [],
      categories: [],
      searchQuery: '',
      selectedCategory: '',
      currentPage: 1,
      itemsPerPage: 10,
      showAddAnimalForm: false,
      showEditForm: false,
      formData: {
        name: '',
        categoryId: '',
        habitat: '',
        description: '',
        endangeredLevel: 0
      },
      editingAnimalId: null
    }
  },
  computed: {
    filteredAnimals() {
      let result = this.animals
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(animal => 
          animal.name.toLowerCase().includes(query)
        )
      }
      
      // 分类过滤
      if (this.selectedCategory) {
        result = result.filter(animal => 
          animal.categoryId === parseInt(this.selectedCategory)
        )
      }
      
      // 分页
      const start = (this.currentPage - 1) * this.itemsPerPage
      const end = start + this.itemsPerPage
      return result.slice(start, end)
    },
    totalPages() {
      let result = this.animals
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(animal => 
          animal.name.toLowerCase().includes(query)
        )
      }
      
      // 分类过滤
      if (this.selectedCategory) {
        result = result.filter(animal => 
          animal.categoryId === parseInt(this.selectedCategory)
        )
      }
      
      return Math.ceil(result.length / this.itemsPerPage)
    }
  },
  mounted() {
    this.fetchAnimals()
    this.fetchCategories()
  },
  methods: {
    fetchAnimals() {
      // 模拟数据，实际应该从API获取
      this.animals = [
        { id: 1, name: '狮子', categoryId: 1, habitat: '非洲草原', description: '大型猫科动物', endangeredLevel: 2, createdAt: '2023-01-15' },
        { id: 2, name: '老虎', categoryId: 1, habitat: '亚洲森林', description: '大型猫科动物', endangeredLevel: 3, createdAt: '2023-02-10' },
        { id: 3, name: '大象', categoryId: 2, habitat: '非洲草原', description: '大型哺乳动物', endangeredLevel: 2, createdAt: '2023-03-05' },
        { id: 4, name: '长颈鹿', categoryId: 2, habitat: '非洲草原', description: '长颈哺乳动物', endangeredLevel: 1, createdAt: '2023-04-20' },
        { id: 5, name: '熊猫', categoryId: 1, habitat: '中国竹林', description: '珍稀熊科动物', endangeredLevel: 2, createdAt: '2023-05-12' },
      ]
    },
    fetchCategories() {
      // 模拟数据，实际应该从API获取
      this.categories = [
        { id: 1, name: '食肉目' },
        { id: 2, name: '长鼻目' },
        { id: 3, name: '奇蹄目' },
        { id: 4, name: '偶蹄目' },
        { id: 5, name: '灵长目' }
      ]
    },
    getCategoryName(categoryId) {
      const category = this.categories.find(c => c.id === categoryId)
      return category ? category.name : '未知'
    },
    getEndangeredText(level) {
      const levels = ['无危', '近危', '易危', '濒危', '极危']
      return levels[level] || '未知'
    },
    getStatusClass(level) {
      const classes = ['status-safe', 'status-near-threatened', 'status-vulnerable', 'status-endangered', 'status-critically-endangered']
      return classes[level] || ''
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },
    logout() {
      localStorage.removeItem('user')
      this.$router.push('/login')
    }
  },
  
  // 监听选中的动物变化，更新全选状态
  watch: {
    selectedAnimals: {
      handler() {
        this.selectAll = this.filteredAnimals.length > 0 && 
                        this.selectedAnimals.length === this.filteredAnimals.length
      },
      deep: true
    },
    
    // 监听筛选条件变化，重置页码和选中状态
    searchQuery() {
      this.currentPage = 1
      this.selectedAnimals = []
      this.selectAll = false
    },
    selectedCategory() {
      this.currentPage = 1
      this.selectedAnimals = []
      this.selectAll = false
    },
    selectedStatus() {
      this.currentPage = 1
      this.selectedAnimals = []
      this.selectAll = false
    }
  }
}
</script>

<style scoped>
/* 样式与DashboardView.vue类似，复用布局样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.add-btn {
  background-color: #27ae60;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: background-color 0.2s;
}

.add-btn:hover {
  background-color: #229954;
}

.search-filter {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.search-input,
.filter-select {
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.filter-select {
  min-width: 150px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #2c3e50;
}

.data-table tbody tr:hover {
  background-color: #f8f9fa;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.85rem;
  font-weight: 500;
}

.status-safe {
  background-color: #d4edda;
  color: #155724;
}

.status-near-threatened {
  background-color: #fff3cd;
  color: #856404;
}

.status-vulnerable {
  background-color: #fff3cd;
  color: #856404;
}

.status-endangered {
  background-color: #f8d7da;
  color: #721c24;
}

.status-critically-endangered {
  background-color: #f5c6cb;
  color: #721c24;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.edit-btn,
.delete-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.edit-btn {
  background-color: #3498db;
  color: white;
}

.edit-btn:hover {
  background-color: #2980b9;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background-color: #c0392b;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 1.5rem;
}

.pagination-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f8f9fa;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 1rem;
  color: #666;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: #f8f9fa;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #2c3e50;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.cancel-btn,
.submit-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #5a6268;
}

.submit-btn {
  background-color: #28a745;
  color: white;
}

.submit-btn:hover {
  background-color: #218838;
}

@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
  }
  
  .search-input {
    max-width: none;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>